﻿using C1.Win.C1Ribbon;
using CWCS.Entity;
using CWCS.Entity.Convery;
using CWCS.Entity.Robot;
using CWCS.UIDesigner.RobotControl;
using CWCS.UIDesigner.ConveryControl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using CWCS.BLL;
using CWCS.Core.Library.PLCManager;
using CWCS.Common.Log;
using CWCS.BLL.WebsocketCommon;
using CWCS.BLL.NTIScModbus;

namespace CWCS.UI
{
    public partial class FrmConveryManager : C1RibbonForm
    {
        DataTable dtSource = new DataTable();
        DataTable dtConfig = new DataTable("ConveryStations");
        BLL.ConveryBLL bll = new BLL.ConveryBLL();
        RobotPLC robotPLC = new RobotPLC();
        ModbusCRCTask CRCTask = new ModbusCRCTask();
        List<BatteryInfo> LstBattery = new List<BatteryInfo>();
        List<CheckInfo> LstCheckInfo = new List<CheckInfo>();
        Dictionary<string, Color> listColor = new Dictionary<string, Color>();
        Dictionary<string, Point> Fulllocations = new Dictionary<string, Point>();
        Dictionary<ConveryStationInfo, ConveryStationsList> LstInfo = new Dictionary<ConveryStationInfo, ConveryStationsList>();
        private Dictionary<string, string> AlarmInfoDic = new Dictionary<string, string>();
        Dictionary<ConveryUnit, DataRow> UnitsConfig = new Dictionary<ConveryUnit, DataRow>();
        List<DataRow> list = new List<DataRow>();
        public Dictionary<string, bool> dicEquipStatus = new Dictionary<string, bool>();
        private delegate void LabelCallBack(string ip, string time, bool b_ConnectStatus);
        private delegate void RichBoxCallBack(RichTextBox rb, string msg);
        private delegate void RichstaCallBack(List<ConveryEntity> lstConvery);
        BatteryControl batteryC = new BatteryControl(null, "", "", 0);
        FrmCheckInfo fcheck = new FrmCheckInfo();
        string scan_barcode = string.Empty;
        string scan_itemcode1 = string.Empty;
        string scan_itemcode2 = string.Empty;
        string itemcode1 = string.Empty;
        string itemcode2 = string.Empty;
        int stationType; 
        private LogHelper staManualLog = new LogHelper("staManualLog");
        Thread P_thread;

        public FrmConveryManager()
        {
            InitializeComponent();
            this.converyPanel1.MouseWheel += new MouseEventHandler(converyPanel1_OnMouseWheel);
        }

        private void FrmConveryManager_Load(object sender, EventArgs e)
        {
            LoadingData();
            bll.ShowStationStatus += new BLL.ConveryBLL.NotifiedUI(ShowConveryStatus);
            bll.ShowLogMsg += new BLL.ConveryBLL.ShowLogMessage(ShowLog);
            bll.ShowStationPLCStatus += new BLL.ConveryBLL.ShowConverysPLCStatus(ShowScanTime);
            bll.ConveryInit();
            //bll.startLED();  不需要LED
            InitAlarmInfo();
            ShowMode();
            tabTray.SelectedIndex = 0;
        }

        private void LoadingData()
        {
            dtSource = bll.GetWCS_OPCItem();
            if (File.Exists("ConveryStations.xml"))
            {
                try
                {
                    dtConfig.ReadXmlSchema("ConveryStations.xml");
                    dtConfig.ReadXml("ConveryStations.xml");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("加载配置文件失败，详细信息：" + ex.Message, "提示");
                    return;
                }
            }
            if (dtConfig.Columns.Count == 0)
            {
                dtConfig.Columns.Add("StationNo");//站台编号
                dtConfig.Columns.Add("StationType");//站台类型
                dtConfig.Columns.Add("locationx");//X
                dtConfig.Columns.Add("locationY");//Y
                dtConfig.Columns.Add("Width");//宽
                dtConfig.Columns.Add("Height");//高
                dtConfig.Columns.Add("Direction");//方向
                dtConfig.Columns.Add("DB");//DB块
                dtConfig.Columns.Add("Length");//DB块长度
                dtConfig.Columns.Add("Value");//DB值
                dtConfig.Columns.Add("IP");//IP地址
                dtConfig.Columns.Add("Belong");//所属线程
                dtConfig.Columns.Add("ZoneCode");//所属区域
            }
            InitConveryStations();
        }

        private void InitAlarmInfo()
        {
            if (File.Exists(".\\ConveryAlarm.txt"))
            {
                FileStream fs = new FileStream(".\\ConveryAlarm.txt", FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string strline = sr.ReadToEnd();
                string[] msg = strline.Split(new char[] { ';' });
                string[] msg2;
                for (int i = 0; i < msg.Length; i++)
                {
                    msg2 = msg[i].Split(new char[] { ',' });
                    if (msg2.Length > 1 && !AlarmInfoDic.ContainsKey(msg2[0]))
                        AlarmInfoDic.Add(msg2[0].Trim(), msg2[1].Trim());
                }
            }
        }
        void InitConveryStations()
        {
            try
            {
                List<DataRow> drNew = new List<DataRow>();
                Color defaultcolor = new ConveryUnitRect().BackColor;
                listColor.Clear();
                listColor.Add("", defaultcolor);
                int count = 0;
                foreach (DataRow dr in dtSource.Select(" 1=1"))
                {
                    ConveryStationInfo csi = new ConveryStationInfo() { X = dr["locationx"].ToString(), Y = dr["locationy"].ToString(), Width = dr["width"].ToString(), Height = dr["height"].ToString(), ConveryNu = dr["itemname"].ToString() };
                    string converyStationNu = dr["stationno"].ToString();
                    if (LstInfo.FirstOrDefault(v => v.Key.Equals(csi)).Value == null)
                    {
                        count++;

                        DataRow[] drs = (dtConfig.Rows.Count > 0 ? dtConfig.Select("stationno='" + dr["stationno"] + "'") : dtSource.Select("1=2"));
                        ConveryUnitRect u;
                        if (drs.Count() > 0)
                        {
                            u = new ConveryUnitRect();
                            u.Visible = false;
                            u.XIndex = Convert.ToInt32(dr["locationx"]);
                            u.YIndex = Convert.ToInt32(dr["locationy"]);
                            u.WidthColumns = Convert.ToInt32(dr["width"]);
                            u.HeightRows = Convert.ToInt32(dr["height"]);

                            u.Data = dr;
                            if (dr["field5"].ToString().Trim() == "1")//入库申请站台
                                u.StationType = ConveryUnit.UnitType.InFeeding;
                            else if (dr["field5"].ToString().Trim() == "2")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.InFeeded;
                            else if (dr["field5"].ToString().Trim() == "3")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.OutFeeding;
                            else if (dr["field5"].ToString().Trim() == "2")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.OutFeeded;
                            else
                                u.StationType = ConveryUnit.UnitType.Normal;
                            if (dr["direction"].ToString().Trim() == "1")//输送机方向
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Vertical;
                            }
                            else if (dr["direction"].ToString().Trim() == "2")
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Horizontal;
                            }
                            else
                                u.Direct = ConveryUnit.UnitOrientation.Empty;

                        }
                        else
                        {
                            u = new ConveryUnitRect();
                            string status = dr["status"].ToString();
                            if (string.IsNullOrEmpty(status))
                                status = "0";
                            if (int.Parse(status) == 1 || int.Parse(status) == 2)
                                u.Visible = true;
                            else
                                u.Visible = false;
                            u.XIndex = Convert.ToInt32(dr["locationx"]);
                            u.YIndex = Convert.ToInt32(dr["locationy"]);
                            u.WidthColumns = Convert.ToInt32(dr["width"]);
                            u.HeightRows = Convert.ToInt32(dr["height"]);
                            u.Data = dr;
                            if (dr["field5"].ToString().Trim() == "1")//入库申请站台
                                u.StationType = ConveryUnit.UnitType.InFeeding;
                            else if (dr["field5"].ToString().Trim() == "2")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.InFeeded;
                            else if (dr["field5"].ToString().Trim() == "3")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.OutFeeding;
                            else if (dr["field5"].ToString().Trim() == "2")//入库到位站台
                                u.StationType = ConveryUnit.UnitType.OutFeeded;
                            else
                                u.StationType = ConveryUnit.UnitType.Normal;
                            if (dr["direction"].ToString().Trim() == "2")//输送机方向
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Vertical;
                            }
                            else if (dr["direction"].ToString().Trim() == "1")
                            {
                                u.Direct = ConveryUnit.UnitOrientation.Horizontal;
                            }
                            else
                                u.Direct = ConveryUnit.UnitOrientation.Empty;
                            if (dr["arrowdirection"].ToString().Trim() == "0")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Empty;
                            if (dr["arrowdirection"].ToString().Trim() == "1")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Right;
                            if (dr["arrowdirection"].ToString().Trim() == "2")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Left;
                            if (dr["arrowdirection"].ToString().Trim() == "3")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Down;
                            if (dr["arrowdirection"].ToString().Trim() == "4")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Up;
                            if (dr["arrowdirection"].ToString().Trim() == "5")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Left_Right;
                            if (dr["arrowdirection"].ToString().Trim() == "6")
                                u.Arrow = ConveryUnit.UnitArrowDirection.Up_Down;
                            if (dr["groupname"].ToString().Trim() == "Convery")
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.Convery;
                            else if (dr["stationtype"].ToString().Trim() == "1" && dr["groupname"].ToString().Trim() == "Robot")
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.PutRobot;
                            else if (dr["stationtype"].ToString().Trim() == "2" && dr["groupname"].ToString().Trim() == "Robot")
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.PickRobot;
                            else
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.Other;
                            if (dr["remark"].ToString().Contains("机械手"))
                            {
                                u.EquipmentType = ConveryUnit.UnitEquipmentType.Robot;
                            }
                        }
                        string text = dr["itemname"].ToString();
                        u.ConveryName = text;
                        u.ConveryNumber= dr["itemid"].ToString();

                        u.Text = csi.ToString();
                        if (!converyPanel1.Units.Exists(it => it.Data == u.Data))
                            converyPanel1.Add(u);

                        ConveryStationsList linfo = new ConveryStationsList();
                        linfo.unit = u;
                        linfo.lcd = csi;
                        LstInfo.Add(csi, linfo);
                        linfo.memo += "站台：" + text;
                        linfo.unit.BackColor = Color.FromArgb(166, 216, 255);
                        if (dr["stationtype"].ToString() == "0")
                            linfo.unit.BackColor = Color.FromArgb(112, 173, 71);
                        if (dr["stationtype"].ToString() == "1")
                            linfo.unit.BackColor = Color.FromArgb(237, 125, 49);
                        if (Convert.ToInt32(dr["stationtype"].ToString()) >= 4)
                            linfo.unit.BackColor = Color.FromArgb(0, 176, 80);
                        if (Convert.ToInt32(dr["stationtype"].ToString()) == 3)
                            linfo.unit.BackColor = Color.FromArgb(68, 114, 196);
                        if (dr["remark"].ToString().Contains("提升机"))
                            linfo.unit.BackColor = Color.FromArgb(91, 155, 213);
                        if (dr["itemname"].ToString().Contains("SC"))
                            linfo.unit.BackColor = Color.FromArgb(255, 255, 0);
                        if (!string.IsNullOrEmpty(dr["remark"].ToString()))
                            linfo.unit.Text = dr["itemname"].ToString() + "\n" + dr["remark"].ToString();
                        if (dr["field5"].ToString() == "1")
                            linfo.unit.Text =  dr["remark"].ToString();
                        if (!dicEquipStatus.ContainsKey(u.ConveryNumber))
                        {
                            dicEquipStatus.Add(u.ConveryNumber, true);
                        }
                    }
                    ConveryStationsList linfo2 = LstInfo.FirstOrDefault(v => v.Key.Equals(csi)).Value;
                    linfo2.rows.Add(dr);
                    linfo2.total++;
                    LstInfo[csi].rows.Add(dr);
                }
                converyPanel1.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Source);
            }
        }

#pragma warning disable CS0659 // “FrmConveryManager.ConveryStationInfo”重写 Object.Equals(object o) 但不重写 Object.GetHashCode()
        struct ConveryStationInfo
#pragma warning restore CS0659 // “FrmConveryManager.ConveryStationInfo”重写 Object.Equals(object o) 但不重写 Object.GetHashCode()
        {
            public string X;
            public string Y;
            public string Width;
            public string Height;
            public string ConveryNu;

            public override bool Equals(object obj)
            {
                ConveryStationInfo csi = (ConveryStationInfo)obj;
                return csi.ConveryNu == this.ConveryNu;
            }
            public override string ToString()
            {
                return this.ConveryNu;
            }

        }

        class ConveryStationsList
        {
            public List<DataRow> rows = new List<DataRow>();
            public int total;
#pragma warning disable CS0649 // 从未对字段“FrmConveryManager.ConveryStationsList.fullConveryStations”赋值，字段将一直保持其默认值 0
            public int fullConveryStations;
#pragma warning restore CS0649 // 从未对字段“FrmConveryManager.ConveryStationsList.fullConveryStations”赋值，字段将一直保持其默认值 0
            public ConveryUnitRect unit;
            public string memo;
            public ConveryStationInfo lcd;
        }

        private void converyPanel1_OnMouseWheel(object sender, MouseEventArgs e)
        {
            if (e.Delta > 0)
            {
                converyPanel1.UnitLW++;
            }
            else
            {
                //if (converyPanel1.UnitLW >= 25)
                //    converyPanel1.UnitLW--;
                if (converyPanel1.UnitLW > 5)
                    converyPanel1.UnitLW--;
            }
            Invalidate();
        }

        private void ShowLog(string type, string msg)
        {
            if (type == "Info")
            {
                ShowText(textLog, msg);
            }
            else
            {
                ShowText(txtWriteLog, msg);
            }
        }

        private void ShowText(RichTextBox rb, string msg)
        {
            if (rb.InvokeRequired)
            {
                RichBoxCallBack rbcb = new RichBoxCallBack(ShowText);
                this.Invoke(rbcb, new object[] { rb, msg });
            }
            else
            {
                if (rb.TextLength > 5000)
                    rb.Clear();
                rb.AppendText(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": " + msg + "\r\n");
            }
        }

        private void ShowConveryStatus(List<ConveryEntity> lstConvery)
        {
            try
            {
                foreach (ConveryEntity convery in lstConvery)
                {
                    ConveryUnit[] unit = converyPanel1.Units.Where(it => it.ConveryNumber == convery.StationNo.ToString()).ToArray();
                    if (unit.Count() > 0)
                    {
                        if (convery.C_TaskInfo.stationno == "1606")
                        {
                            
                        }
                        if (convery.C_TaskInfo.tasknum >= 1)
                        {
                            if (convery.C_TaskInfo.gooodstype == 0)
                                unit[0].GoodsType = ConveryUnitRect.UnitGoodsType.EmptyPallet;
                            else if (convery.C_TaskInfo.gooodstype == 1)
                                unit[0].GoodsType = ConveryUnitRect.UnitGoodsType.EmptyPallet;
                            else if (convery.C_TaskInfo.gooodstype > 1)
                                unit[0].GoodsType = ConveryUnitRect.UnitGoodsType.Realpallet;
                        }
                        if ((convery.C_TaskInfo.gooodstype == 0 || convery.C_TaskInfo.checkinfo == 1) && (convery.C_TaskInfo.tasknum == 0 || convery.C_TaskInfo.stationtype == 16))
                            unit[0].GoodsType = ConveryUnitRect.UnitGoodsType.Empty;
                        else if (string.IsNullOrEmpty(convery.C_TaskInfo.barcode) && convery.C_TaskInfo.tasknum >= 1 && convery.C_TaskInfo.stationtype != 16)
                            unit[0].GoodsType = ConveryUnitRect.UnitGoodsType.ReRealpallet;
                        if (convery.C_TaskInfo.faultflag != 100&& convery.C_TaskInfo.faultflag != 0)
                            unit[0].EuipmentState = ConveryUnitRect.UnitEuipmentState.Error;
                        else
                            unit[0].EuipmentState = ConveryUnitRect.UnitEuipmentState.OK;
                        if (convery.C_TaskInfo.datatype == "SCAN" && convery.C_TaskInfo.mode == "1" && convery.C_TaskInfo.tostation == Int32.Parse(convery.C_TaskInfo.stationno))
                        {
                            if (convery.C_TaskInfo.barcode != convery.C_TaskInfo.scanbarcode)
                                unit[0].EuipmentState = ConveryUnitRect.UnitEuipmentState.Error;
                        }
                        if (convery.C_TaskInfo.datatype == "SCAN" && convery.C_TaskInfo.mode == "2" && convery.C_TaskInfo.tostation == Int32.Parse(convery.C_TaskInfo.stationno))
                        {
                            scan_itemcode1 = bll.getItemcodeByPalltecode(convery.C_TaskInfo.barcode, bll.ZoneCode)[0];
                            scan_itemcode2 = bll.getItemcodeByPalltecode(convery.C_TaskInfo.barcode, bll.ZoneCode)[1];
                            if (convery.C_TaskInfo.scanitemcode1 != scan_itemcode1  && !convery.C_TaskInfo.scanitemcode1.StartsWith("WCS")
                               || convery.C_TaskInfo.scanitemcode2 != scan_itemcode2  && !convery.C_TaskInfo.scanitemcode2.StartsWith("WCS"))
                                unit[0].EuipmentState = ConveryUnitRect.UnitEuipmentState.Error;
                        }
                        unit[0].Data = convery.C_TaskInfo;
                        //if (convery.C_TaskInfo.Error != "0")
                        //    unit[0].EuipmentState = ConveryUnitRect.UnitEuipmentState.Error;
                        //else
                        //    unit[0].EuipmentState = ConveryUnitRect.UnitEuipmentState.OK;


                        if (unit[0].EuipmentState == ConveryUnitRect.UnitEuipmentState.Error)
                        {
                            dicEquipStatus[unit[0].ConveryNumber] = false;
                            string msg = convery.C_TaskInfo.stationno + "输送机站台故障";
                            QueueSpeech.AddQueue(msg);
                        }
                        else
                        {
                            dicEquipStatus[unit[0].ConveryNumber] = true;
                        }
                    }
                }

                ConveryUnit[] unitRobots = converyPanel1.Units.Where(it => it.EquipmentType == ConveryUnitRect.UnitEquipmentType.Robot).ToArray();
                foreach (var unitRobot in unitRobots)
                {
                    var info = robotPLC.getRobotStatus(unitRobot.ConveryName);
                    if (int.Parse(info) != 1)
                    {
                        unitRobot.EuipmentState = ConveryUnit.UnitEuipmentState.Error;
                    }
                    else
                        unitRobot.EuipmentState = ConveryUnit.UnitEuipmentState.OK;
                }

                ConveryUnit[] unitSCs = converyPanel1.Units.Where(it => it.ConveryName.Contains("SC")).ToArray();
                foreach (var unitSC in unitSCs)
                {
                    CRCStatus SrmInfo = ModbusCRCTask.list_srm_info.Find(
                 delegate (CRCStatus info)
                 {
                     return unitSC.ConveryName.Contains(info.scno);
                 }
                  );
                    if (SrmInfo != null)
                    {
                        if (SrmInfo.SCStatus == "Equipment_Error")
                            unitSC.EuipmentState = ConveryUnit.UnitEuipmentState.Error;
                        else
                            unitSC.EuipmentState = ConveryUnit.UnitEuipmentState.OK;
                    }
                    else
                        unitSC.EuipmentState = ConveryUnit.UnitEuipmentState.Error;
                }
                converyPanel1.Invalidate();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Source);
            }
        }
        private void ShowScanTime(string strIP, string strDuration, bool b_ConnectStatus)
        {
            if (txt_scantime.InvokeRequired)
            {
                LabelCallBack lcb = new LabelCallBack(ShowScanTime);
                this.Invoke(lcb, new object[] { strIP, strDuration, b_ConnectStatus });
            }
            else
            {
                if (b_ConnectStatus)
                {
                    txt_scantime.BackColor = txt_scantime.BackColor == Color.Lime ? Color.DarkGray : Color.Lime;
                    txt_scantime.Text = strDuration;
                }
                else
                {
                    txt_scantime.BackColor = Color.Red;
                    txt_scantime.Text = strIP;
                }
            }
        }

        private void converyPanel1_UnitMouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                btnConfrim.Enabled = true;
                ConveryUnit u = (ConveryUnit)sender;
                if (u != null)
                {
                    ConveryTaskInfo cs = u.Data as ConveryTaskInfo;
                    if (cs == null)
                        return;
                    stationType = cs.stationtype;
                    txtStationNum.Text = cs.stationno;
                    txtTaskNum.Text = cs.tasknum.ToString();
                    txtBarCode.Text = cs.barcode.Trim();
                    txtGoodsType.Text = cs.gooodstype.ToString();
                    txtFromStation.Text = cs.fromstation.ToString();
                    txtToStation.Text = cs.tostation.ToString();
                    textLoad.Text = cs.stationtype == 6 ? cs.checkinfo.ToString() == "1" ? "允许" : "拒绝" : cs.checkinfo.ToString();
                    textScanBarcode.Text = cs.datatype == "SCAN" && cs.mode=="1" ? cs.scanbarcode.Trim() : cs.barcode.Trim();
                    if (AlarmInfoDic.ContainsKey(cs.faultflag.ToString()))
                    {
                        richTextBox_alarm.Text = AlarmInfoDic[cs.faultflag.ToString()];
                    }
                    else
                        richTextBox_alarm.Text = "未知故障";
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                if (!string.IsNullOrEmpty(txtBarCode.Text.Trim()) && txtBarCode.Text.Trim().Length == 11)
                {
                    DataTable dt = bll.GetBatteryCodeByTrayCode(txtBarCode.Text.Trim());
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        LstBattery.Clear();
                        foreach (DataRow dr in dt.Rows)
                        {
                            BatteryInfo battery = new BatteryInfo();
                            battery.BatteryCode = dr["itemcode"].ToString().StartsWith("WCS") ? "" : dr["itemcode"].ToString();
                            battery.BatteryResult = string.IsNullOrEmpty(dr["tobaccotype"].ToString()) ? dr["bindresult"].ToString() : dr["tobaccotype"].ToString();
                            battery.Position = int.Parse(dr["sequenceno"].ToString());
                            LstBattery.Add(battery);
                        }
                        batteryC.ShowData(txtBarCode.Text.Trim(), LstBattery);
                        batteryC.ShowDialog();
                    }
                    else
                        MessageBox.Show("获取组盘数据异常，请选择正确托盘：" + txtBarCode.Text);
                }
                else
                    MessageBox.Show("托盘编号为空或长度异常，请先选择正确站台！");
            }
        }

        private void btnConfrim_Click(object sender, EventArgs e)
        {
            try
            {
                //if (!BLLBase.loginFlag)
                //{
                //    FrmLogIn frmLogIn = new FrmLogIn();
                //    frmLogIn.ShowDialog();
                //}
                //if (!BLLBase.loginFlag)
                //{
                //    MessageBox.Show("用户校验失败,请重新校验!");
                //    return;
                //}
                BLLBase.loginTime = DateTime.Now;
                if (!System.String.IsNullOrEmpty(txtStationNum.Text.Trim()))
                {
                    string[] str = new string[10];
                    str[0] = txtStationNum.Text.Trim();
                    str[1] = txtTaskNum.Text.Trim(); //任务号
                    str[2] = txtBarCode.Text.Trim(); //托盘条码
                    str[3] = txtGoodsType.Text.Trim();//货物类型
                    str[4] = txtFromStation.Text.Trim();//起始地址
                    str[5] = txtToStation.Text.Trim();//目标地址
                    if (str[5] != "1" && str[5] != "0" && str[5] != "9999")
                    {
                        if (!bll.UpdateItempalletTostation(str[2], str[5]))
                        {
                            staManualLog.Info("用户:" + BLLBase.user + "手动修改目标地址,更新Itempallet表中托盘:'" + str[2] + "'的目标地址失败,请检查该托盘是否初始化!");
                        }
                    }
                    if (bll.WriteStationInfo(str, txtStationNum.Text.Trim()))
                    {
                        staManualLog.Info("用户:" + BLLBase.user + "修改站台:" + str[0] + "数据为:任务号" + str[1] + "托盘条码：" + str[2] + "货物类型：" + str[3] + "目标地址：" + str[5]);
                        btnConfrim.Enabled = true;
                        MessageBox.Show("修改成功！");
                    }
                    else
                    {
                        MessageBox.Show("修改失败！");
                    }
                }
            }
            catch { }
        }

        private void converyPanel1_UnitMouseEnter(object sender, EventArgs e)
        {
            ConveryUnit u = (ConveryUnit)sender;
            if (u != null)
            {
                ConveryTaskInfo ct = (ConveryTaskInfo)u.Data;

                this.toolTip1.ToolTipTitle = "站台信息";
                this.toolTip1.IsBalloon = false;
                this.toolTip1.UseFading = true;
                if (u.EuipmentState == CWCS.UIDesigner.ConveryControl.ConveryUnit.UnitEuipmentState.Error)
                {

                    //this.toolTip1.Show("站台:" + ct.stationno + "运行超时", this.converyPanel1, 2000);
                }
                else
                {
                    this.toolTip1.Show("站台:" + ct.stationno + "\r\n任务号：" + ct.stationno + "\r\n托盘:" + ct.barcode + "\r\n" + "起始地址：" + ct.fromstation + "\r\n目标地址：" + ct.tostation, this.converyPanel1, 2000);
                }
            }
        }

        private void c1Button2_Click(object sender, EventArgs e)
        {
            try
            {
                //if (!BLLBase.loginFlag)
                //{
                //    FrmLogIn frmLogIn = new FrmLogIn();
                //    frmLogIn.ShowDialog();
                //}
                //if (!BLLBase.loginFlag)
                //{
                //    MessageBox.Show("用户校验失败,请重新校验!");
                //    return;
                //}
                BLLBase.loginTime = DateTime.Now;

                if (!System.String.IsNullOrEmpty(txtStationNum.Text.Trim()))
                {
                    string[] str = new string[10];
                    str[0] = "0";
                    str[1] = "0";
                    str[2] = "0";
                    str[3] = "0";
                    str[4] = "0";
                    str[5] = "0";
                    if (bll.WriteStationInfo(str, txtStationNum.Text.Trim()))
                    {
                        staManualLog.Info("用户:" + BLLBase.user + "清空站台:" + txtStationNum.Text.Trim() + "数据成功!");
                        btnConfrim.Enabled = true;
                        MessageBox.Show("清空成功！");
                    }
                    else
                    {
                        MessageBox.Show("清空失败！");
                    }
                }
            }
            catch { }
        }

        private void c1Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (!BLLBase.loginFlag)
                {
                    FrmLogIn frmLogIn = new FrmLogIn();
                    frmLogIn.ShowDialog();
                }
                if (!BLLBase.loginFlag)
                {
                    MessageBox.Show("用户校验失败,请重新校验!");
                    return;
                }
                BLLBase.loginTime = DateTime.Now;
                if (!System.String.IsNullOrEmpty(txtStationNum.Text.Trim()))
                {
                    string scanInfo = textScanBarcode.Text.Trim();
                    if (bll.WriteScanInfo(scanInfo, txtStationNum.Text.Trim()))
                    {
                        staManualLog.Info("用户:" + BLLBase.user + "手动补码成功!站台:" + txtStationNum + ",条码:" + scanInfo);
                        btnConfrim.Enabled = true;
                        MessageBox.Show("补码成功！");
                    }
                    else
                    {
                        MessageBox.Show("补码失败！");
                    }
                }
            }
            catch { }
        }

        private void c1Button3_Click(object sender, EventArgs e)
        {
            if (!BLLBase.loginFlag)
            {
                FrmLogIn frmLogIn = new FrmLogIn();
                frmLogIn.ShowDialog();
            }
            if (!BLLBase.loginFlag)
            {
                MessageBox.Show("用户校验失败,请重新校验!");
                return;
            }
            BLLBase.loginTime = DateTime.Now;

            string strMode = comboBox1.Text.Trim();

            if (strMode == "--请选择--")
            {
                MessageBox.Show("请选择模式！");
                return;
            }
            else if (strMode == "空托投入")
            {
                BLLBase.Mode = 1;
            }
            else if (strMode == "绑盘投入")
            {
                BLLBase.Mode = 2;
            }
            else if (strMode == "托盘续接")
            {
                BLLBase.Mode = 3;
            }
            else
            {
                MessageBox.Show("模式错误！");
                return;
            }
            BLLBase.modeName = strMode;
            textBox1.Text = BLLBase.modeName;
            BLLBase.modeTime = DateTime.Now;
            MessageBox.Show("修改投盘模式成功！");
            staManualLog.Info("用户:" + BLLBase.user + "将投盘模式修改成:" + strMode);
        }

        private void ShowMode()
        {
            try
            {
                P_thread = new Thread(
                    () =>
                    {
                        while (true)
                        {
                            this.Invoke(
                                (MethodInvoker)delegate ()
                                //在对控件的 Invoke 方法进行调用时或需要一个简单委托又不想自己定义时可以使用该委托。   
                                {
                                    if (int.Parse(DateTime.Now.Subtract(BLLBase.modeTime).Duration().Minutes.ToString()) >= BLLBase.ActivieModeime)
                                    {
                                        BLLBase.Mode = 0;
                                        BLLBase.modeName = "无模式";
                                    }
                                    if (BLLBase.ocvMsaStatus)
                                    {
                                        this.c1Button5.Text = "开启";
                                        this.c1Button5.BackColor = Color.Green;
                                    }
                                    else
                                    {
                                        this.c1Button5.Text = "关闭";
                                        this.c1Button5.BackColor = Color.Red;
                                    }
                                    var OCVMAS = Newtonsoft.Json.JsonConvert.SerializeObject(BLLBase.ocvMsaStatus);
                                    WebSocketHelper.SendMsgToRemotePoint("ShowOCVMAS" + OCVMAS);

                                    var modeName = Newtonsoft.Json.JsonConvert.SerializeObject(BLLBase.modeName);
                                    WebSocketHelper.SendMsgToRemotePoint("ShowMode" + modeName);
                                    this.textBox1.Text = BLLBase.modeName;
                                });
                            Thread.Sleep(1000);
                        }
                    });
                P_thread.IsBackground = true;
                P_thread.Start();
            }
            catch (Exception e)
            {

            }
        }

        private void c1Button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (!BLLBase.loginFlag)
                {
                    FrmLogIn frmLogIn = new FrmLogIn();
                    frmLogIn.ShowDialog();
                }
                if (!BLLBase.loginFlag)
                {
                    MessageBox.Show("用户校验失败,请重新校验!");
                    return;
                }
                BLLBase.loginTime = DateTime.Now;
                if (!System.String.IsNullOrEmpty(txtStationNum.Text.Trim()) && txtStationNum.Text.Trim().Length == 4)
                {
                    string[] str = new string[10];
                    str[0] = textBox2.Text.Trim();
                    str[1] = txtTaskNum.Text.Trim(); //任务号
                    str[2] = txtBarCode.Text.Trim(); //托盘条码
                    str[3] = txtGoodsType.Text.Trim();//货物类型
                    str[4] = txtFromStation.Text.Trim();//起始地址
                    str[5] = txtToStation.Text.Trim();//目标地址
                    if (bll.WriteStationInfo(str, textBox2.Text.Trim()))
                    {
                        staManualLog.Info("用户:" + BLLBase.user + "转移站台:" + txtStationNum.Text.Trim() + "数据至站台:" + str[0] + "成功,数据为托盘条码：" + str[2] + "货物类型：" + str[3] + "目标地址：" + str[5]);
                        btnConfrim.Enabled = true;
                        MessageBox.Show("转移成功！");
                    }
                    else
                    {
                        MessageBox.Show("转移失败！");
                    }
                }
            }
            catch { }
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            try
            {
                if (!BLLBase.loginFlag)
                {
                    FrmLogIn frmLogIn = new FrmLogIn();
                    frmLogIn.ShowDialog();
                }
                if (!BLLBase.loginFlag)
                {
                    MessageBox.Show("用户校验失败,请重新校验!");
                    return;
                }
                BLLBase.loginTime = DateTime.Now;

                if (!System.String.IsNullOrEmpty(txtStationNum.Text.Trim()) && txtStationNum.Text.Trim().Length == 4)
                {
                    
                    string exceptionstation = string.Empty;
                    if (BLLBase.getExceptionTostation(txtStationNum.Text.Trim(), ref exceptionstation))
                    {

                        if (stationType != 3 && stationType != 4 && stationType != 7 && stationType != 8)
                        {
                            MessageBox.Show("站台:" + txtStationNum.Text.Trim() + "不支持一键排异功能,请手动将托盘送至最近任务申请口!");
                            return;
                        }
                        string[] str = new string[6];
                        str[0] = txtStationNum.Text.Trim();
                        str[1] = "1001"; //任务号
                        str[2] = txtBarCode.Text.Trim(); //托盘条码
                        str[3] = "4";
                        str[4] = txtStationNum.Text.Trim();//起始地址
                        str[5] = stationType == 4 ? txtStationNum.Text.Trim() : exceptionstation;//目标地址
                        if (bll.WriteStationInfo(str, txtStationNum.Text.Trim()))
                        {
                            if (!bll.UpdateItempalletTostation(str[2], str[5]))
                            {
                                staManualLog.Info("用户:" + BLLBase.user + "一键排异,更新Itempallet表中托盘:'" + str[2] + "'的目标地址失败,请检查该托盘是否初始化!");
                            }
                            staManualLog.Info("用户:" + BLLBase.user + "将站台:" + txtStationNum.Text.Trim() + "上托盘一键排出至异常口,站台数据为托盘条码：" + str[2] + "货物类型：" + str[3] + "目标地址：" + str[5]);
                            MessageBox.Show("一键排异成功!");
                        }
                    }
                    else
                    {
                        staManualLog.Info("用户:" + BLLBase.user + "使用站台:" + txtStationNum.Text.Trim() + "一键排出至异常口,未配置异常口!");
                        MessageBox.Show("站台:" + txtStationNum.Text.Trim() + "没有配置异常口!");
                        return;
                    }
               }
            }
            catch 
            {

            }
        }

        private void c1Button5_Click(object sender, EventArgs e)
        {
            if (!BLLBase.loginFlag)
            {
                FrmLogIn frmLogIn = new FrmLogIn();
                frmLogIn.ShowDialog();
            }
            if (!BLLBase.loginFlag)
            {
                MessageBox.Show("用户校验失败,请重新校验!");
                return;
            }
            BLLBase.loginTime = DateTime.Now;

            if (this.c1Button5.Text == "关闭")
            {
                this.c1Button5.Text = "开启";
                this.c1Button5.BackColor = Color.Green;
                BLLBase.ocvMsaStatus = true;
            }
            else
            {
                this.c1Button5.Text = "关闭";
                this.c1Button5.BackColor = Color.Red;
                BLLBase.ocvMsaStatus = false;
                BLLBase.ocvMsa.Clear();
            }
            staManualLog.Info("用户:" + BLLBase.user + (BLLBase.ocvMsaStatus ? "开启" : "关闭") + "MSA功能");
        }
    }
}
